﻿using System;

namespace Slc.Core.Entity
{
    public class OQL3 : OQL4, IOQL3
    {
        private OQL CurrentOQL;
        public OQL3(OQL oql)
            : base(oql)
        {
            CurrentOQL = oql;
        }
        public OQL4 Having(object field, object Value, string sqlFunctionFormat)
        {
            if (string.IsNullOrEmpty(sqlFunctionFormat))
                throw new ArgumentNullException("SQL 格式函数不能为空！");
            if (sqlFunctionFormat.Contains("--") || sqlFunctionFormat.Contains("\'"))
                throw new ArgumentException("SQL 格式函数不合法！");
            if (sqlFunctionFormat.Contains("{0}") && sqlFunctionFormat.Contains("{1}"))
            {
                var tnf = CurrentOQL.TakeOneStackFields();
                string fieldName = tnf.Field;
                string paraName = CurrentOQL.CreateParameter(tnf);
                string havingString = string.Format(sqlFunctionFormat, fieldName, paraName);
                CurrentOQL.oqlString += "\r\n             HAVING " + havingString;
                return new OQL4(CurrentOQL);
            }
            throw new ArgumentException("SQL 格式函数要求类似这样的格式：SUM({0}) > {1}");
        }

        public OQL4 Having(OQLCompareFunc cmpFun)
        {
            OQLCompare compare = new OQLCompare(this.CurrentOQL);
            OQLCompare cmpResult = cmpFun(compare);

            if (!object.Equals(cmpResult, null))
            {
                CurrentOQL.oqlString += "\r\n             HAVING " + cmpResult.CompareString;
            }
            return new OQL4(CurrentOQL);
        }
    }
}
